package org.stvd.controller.oauth;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.Consts;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.dto.QueryResult;
import org.stvd.core.util.DateUtil;
import org.stvd.entities.oauth.OauthClientDetails;
import org.stvd.service.admin.RolesService;
import org.stvd.service.oauth.OauthClientDetailsService;

import net.sf.json.JSONObject;

/**
 * Oauth授权客户端-控制类
 * @author sunzhifeng
 */
@Controller
@RequestMapping("/oauth/oauthclient")
public class OauthClientController extends BaseController {

    @Autowired
    private OauthClientDetailsService oauthClientDetailsService;// 授权客户端Service
    @Autowired
    private RolesService rolesService;

    private String tmpURL = "/oauth/oauthclient/";

    /**
     * 授权客户端管理GET/POST
     * @param oauthClientDetails
     * @return
     */
    @RequestMapping(value = "manage")
    public String onPageLoad(@ModelAttribute("oauthClientDetails") OauthClientDetails oauthClientDetails) {
        QueryResult<OauthClientDetails> queryResult = oauthClientDetailsService.queryOauthClientResult(
            (pageNo - 1) * pageSize, pageSize, oauthClientDetails.getClientId(), oauthClientDetails.getClientName());
        map.put("queryResult", queryResult);
        return tmpURL + "OauthClientManage.html";
    }

    /**
     * 授权客户端新增
     * @param oauthClientDetails
     * @return
     */
    @GetMapping(value = "add")
    public String onOauthClientAddLoad(@ModelAttribute("oauthClientDetails") OauthClientDetails oauthClientDetails) {
        map.put("roles", rolesService.getRolesByUserId(SecurityUserHolder.getCurrentUserId(), Consts.GUID));
        return tmpURL + "OauthClientAdd.html";
    }

    @Log(title = "新增授权客户端", businessType = BusinessType.INSERT)
    @PostMapping(value = "add")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onOauthClientAddAction(
        @Valid @ModelAttribute("oauthClientDetails") OauthClientDetails oauthClientDetails, 
        BindingResult bindingResult) throws Exception {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        boolean hasError = false;
        if (bindingResult.hasErrors()) {
            hasError = true;
        }
        if (!hasError) {
            if (oauthClientDetailsService.hasOauthClientId(oauthClientDetails.getClientId())) {
                bindingResult.addError(new ObjectError("DATA_ERROR", "当前clientId已存在！"));
                hasError = true;
            } else {
                oauthClientDetails.setCreateTime(DateUtil.getSystemDate());
                oauthClientDetails.setScope("read,write");
                oauthClientDetails.setClientSecret(oauthClientDetailsService.generateSecret());
                oauthClientDetails.setAdditionalInformation(
                    "{\"allowedIp\":\"" + oauthClientDetails.getAdditionalInformation() + "\"}");
                oauthClientDetailsService.insert(oauthClientDetails);
            }
        }
        if (hasError) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        map.clear();
        result.setMsg("新增成功！");
        return result;
    }

    /**
     * 授权客户端修改
     * 
     * @param clientId
     * @param oauthClientDetails
     * @return
     */
    @GetMapping(value = "edit/{clientId}")
    public String onOauthClientEditLoad(@PathVariable String clientId,
        @ModelAttribute("oauthClientDetails") OauthClientDetails oauthClientDetails) {
        map.put("roles", rolesService.getRolesByUserId(SecurityUserHolder.getCurrentUserId(), Consts.GUID));
        oauthClientDetails = oauthClientDetailsService.findByPk(OauthClientDetails.class, clientId);
        if (oauthClientDetails == null) {
            map.put("errorMsg", "授权客户端信息获取失败，请返回重试");
        } else {
            try {
                oauthClientDetails.setAdditionalInformation(
                    JSONObject.fromObject(oauthClientDetails.getAdditionalInformation()).getString("allowedIp"));
            } catch (Exception ex) {
                oauthClientDetails.setAdditionalInformation("");
            }
            map.put("oauthClientDetails", oauthClientDetails);
        }
        return tmpURL + "OauthClientEdit.html";
    }

    @Log(title = "修改授权客户端", businessType = BusinessType.UPDATE)
    @PostMapping(value = "edit")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onOauthClientEditActive(
        @Valid @ModelAttribute("oauthClientDetails") OauthClientDetails oauthClientDetails,
        BindingResult bindingResult) throws Exception {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        Boolean bHasError = false;
        if (bindingResult.hasErrors()) {
            bHasError = true;
        }
        if (!bHasError) {
            oauthClientDetails
                .setAdditionalInformation("{\"allowedIp\":\"" + oauthClientDetails.getAdditionalInformation() + "\"}");
            oauthClientDetailsService.update(oauthClientDetails);
        }
        if (bHasError) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        map.clear();
        result.setMsg("修改成功！");
        return result;
    }

    /**
     * 授权客户端删除
     * @param clientId
     * @return
     */
    @Log(title = "删除授权客户端", businessType = BusinessType.DELETE)
    @PostMapping(value = "del")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onOauthClientDelete(String clientId) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            oauthClientDetailsService.delete(OauthClientDetails.class, clientId);
            result.setMsg("删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("删除失败！<br/>失败原因：" + e.getMessage());
        }
        return result;
    }
    
    /**
     * @Description: 生成密钥
     * @return
     */
    @GetMapping(value = "createSecret")
    @ResponseBody
    public String onBuildSecret() {
        return oauthClientDetailsService.generateSecret();
    }

}
